import { Component, OnInit, ViewChild } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
import { ProblemAnalyseComponent } from "../+problem-analyse/problem-analyse.component"

declare var $: any;
declare var Viewer: any;

@Component({
    selector: 'sa-fault-problem-detail',
    templateUrl: './fault-problem-detail.component.html',
    styleUrls: ['./fault-problem-detail.css']
})
export class FaultProblemDetailComponent implements OnInit {
    tableData: any[] = []; //table数据
    totalCount: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    searchKey: string = ''; //搜索keyword

    selectedCompanyName: string = ''; //公司名称
    selectedCompanyId: string = ''; //公司ID
    selectCarNumber: string = ''; // 车牌号
    selectDeviceId: string = ''; // 设备ID
    questionType: string = '1'; // 故障类型
    faultmList: any = []; //弹窗问题暂存
    singleData: any = '';  //表格单条数据暂存
    fault_startTime: string = '';
    fault_endTime: string = '';
    specifyId2 = {
        picker1: 'datetimepicker5',
        picker2: 'datetimepicker6'
    }
    specifyTime2 = {
        startTime: '',
        endTime: '',
    }
    @ViewChild("analyseComponent")
    parentAnalyseComponent: ProblemAnalyseComponent
    inputCompanyTreeCarData: any = {};//车辆运行状态模块跳转该页面传递过来的参数

    sanitationQuestionType = '' // 环卫问题类型，只有列表头部选择环卫问题才有
    sanitationQuestionEnum = [
        { value: '1', label: '传感器信号异常' },
        { value: '2', label: '接近开关1损坏' },
        { value: '3', label: '接近开关2损坏' },
        { value: '4', label: '接近开关1/2均损坏' },
        { value: '5', label: 'CAN板异常' },
        { value: '6', label: '重量异常' },
        { value: '7', label: '漏桶标记' },
    ]


    constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
        activatedRoute.queryParams.subscribe(queryParams => {
            this.curPage = queryParams.nowPage || 1;
            if (queryParams.companyId) {
                this.selectedCompanyId = queryParams.companyId;
                this.inputCompanyTreeCarData.companyId = queryParams.companyId;
            }
            if (queryParams.companyName) {
                this.selectedCompanyName = queryParams.companyName;
                this.inputCompanyTreeCarData.companyName = queryParams.companyName;
            }
            this.inputCompanyTreeCarData.carNumber = '';
            this.inputCompanyTreeCarData.deviceId = ''
        });
    }

    ngOnInit() {
        // 分析处理可拖拽
        this.modalMove();

        this.load();
    }

    //table刷新
    refresh() {
        this.load();
    }
    //分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }

    //表格搜索
    table_search() {
        this.curPage = 1;
        this.searchKey = common.stringTrim(this.searchKey);
        this.load();
    }
    //初始化加载list数据
    load() {
        const parameters: any = {
            companyId: this.selectedCompanyId,
            deviceId: this.selectDeviceId,
            carNumber: this.selectCarNumber,
            questionType: this.questionType,
            searchKey: common.stringTrim(this.searchKey),
            startTime: this.fault_startTime,
            endTime: this.fault_endTime
        }
        if (this.questionType === '3') {
            parameters.sanitationQuestionType = this.sanitationQuestionType
        }
        let data = {
            pageSize: this.pageSize,
            nowPage: this.curPage,
            parameters
        }
        let reqdata = 'gridPager=' + JSON.stringify(data);
        this.jsonApiService.http("saniDeviceMark/deviceMarkList.html", reqdata).subscribe(data => {
            this.tableData = data.exhibitDatas;
            this.totalCount = data.recordCount;

            for (let item of data.exhibitDatas) {  //遍历环卫问题列表
                if (item.sanitationProblemEntity && item.sanitationProblemEntity.problem && this.questionType == '3') {
                    let newProblem: any = [];
                    item.sanitationProblemEntity.problem.map((element, index) => {
                        if (element > 0) {
                            switch (index) {
                                case 0:
                                    newProblem.push("传感器信号异常");
                                    break;
                                case 1:
                                    if (element === 1) {
                                        newProblem.push("接近开关1损坏")
                                    } else if (element === 2) {
                                        newProblem.push("接近开关2损坏");
                                    } else if (element === 3) {
                                        newProblem.push("接近开关1/2均损坏");
                                    }
                                    break;
                                case 2:
                                    newProblem.push("CAN板异常");
                                    break;
                                case 3:
                                    newProblem.push("重量异常");
                                    break;
                                case 4:
                                    newProblem.push("漏桶标记");
                                    break;
                            }
                        }
                    });
                    item.sanitationProblemEntity.problem = newProblem;
                }
            }
        })
    }

    tabChange(type) {
        this.questionType = type;
        this.curPage = 1;
        this.pageSize = 10;
        this.tableData = [];
        this.searchKey = ''
        this.load();
    }
    //公司选中回调
    companySelected(data) {
        this.selectedCompanyId = data.companyId;
        this.selectedCompanyName = data.companyName;
        this.selectCarNumber = data.carNumber;
        this.selectDeviceId = data.deviceId;

        if (!data.companyId) {
            var url = window.location.href;
            if (url.indexOf('?') != -1) {
                var index = url.lastIndexOf("?");
                var urlStr = url.substring(index + 1, url.length);
                url = url.replace('?' + urlStr, '');

                window.location.href = url;
            }
        }

        this.load();
    }


    // 列表查看详情的弹框
    showDetailModal(row, modal) {
        this.faultmList = [];
        if (row.sensorProblemList && this.questionType == '1') {
            this.faultmList = row.sensorProblemList;
        } else if (row.gpsProblemEntity && this.questionType == '2') {
            this.faultmList.push(row.gpsProblemEntity);
        } else if (row.sanitationProblemEntity && this.questionType == '3') {
            this.faultmList.push(row.sanitationProblemEntity);
        }
        modal.show();
        this.singleData = row;
    }

    itemModalClose(modal) {
        this.faultmList = [];
        this.singleData = '';
        modal.hide()
    }
    //导出
    exportData() {
        const parameters: any = {
            deviceId: this.selectDeviceId,
            carNumber: this.selectCarNumber,
            companyId: this.selectedCompanyId,
            companyName: this.selectedCompanyName,
            searchKey: common.stringTrim(this.searchKey),
            questionType: this.questionType,
            startTime: this.fault_startTime,
            endTime: this.fault_endTime
        };
        if (this.questionType === '3') {
            parameters.sanitationQuestionType = this.sanitationQuestionType
        }
        // let timeCheck = common.correctTime(parameters, ['questionType'])  //时间选择提示
        // if(!timeCheck.status){
        // 	this.jsonApiService.message(timeCheck.message);
        // 	return;
        // }
        common.exprotDataFile(parameters, 'param', config.BaseURL + 'saniDeviceMark/exportDeviceStateFile.html')
    }
    // 接收子组件传递过来的数据
    getSelectTableTime(time) {
        this.fault_startTime = time.startTime;
        this.fault_endTime = time.endTime;
    }

    /**
     * 数据分析处理
    */

    //数据分析处理
    showDataModal(row, modal) {
        this.faultmList = [];
        modal.hide();

        this.singleData.companyName = this.singleData.parentName;
        this.singleData.initTime = true;
        this.singleData.initStartTime = row.startTime;
        this.singleData.initEndTime = row.endTime;

        // 公司和车辆回显
        this.parentAnalyseComponent.initCompanyAndCar(this.singleData)

        // 弹框展示
        $('#analyseModal').show();
        $(window).trigger("resize")
    }

    //关闭分析处理 弹框
    cancelAnalyseModal() {
        $('#analyseModal').hide();
        this.singleData = '';
    }

    //分析处理弹框拖动事件
    modalMove() {
        var that = this;
        $('body').undelegate('#analyseModalheadDrag', 'mousedown', function () { });
        $('body').delegate('#analyseModalheadDrag', 'mousedown', function (e) {
            $(this).css("cursor", "move");
            var offset = $('#analyseModal').position();
            var x = e.pageX - offset.left;
            var y = e.pageY - offset.top;
            $(document).bind("mousemove", function (ev) {
                $("#analyseModal").stop();
                var _x = ev.pageX - x;
                var _y = ev.pageY - y;
                if (_y < 0) { //避开头部横条
                    return;
                }
                $("#analyseModal").animate({
                    left: _x + "px",
                    top: _y + "px"
                }, 2);
            });
        });
        $(document).mouseup(function (e) {
            e.cancelBubble = true;
            $(this).unbind("mousemove");
        });
        $('body').undelegate('#dragArrow', 'mousedown', function () { });
        $('body').delegate('#dragArrow', 'mousedown', function (e) {
            let ele = $('#analyseModal');
            let x = e.pageX - ele.width();
            $('body').bind("mousemove", function (ev) {
                $("#analyseModal").stop();
                let _x = ev.pageX - x;
                if (_x < 1200) { //避开头部横条
                    return;
                }
                $("#analyseModal").find('.modal-dialog').animate({
                    width: _x + "px",
                }, 2);
                //				setTimeout(()=>{
                let W = $('#popContent').width() - 2;

                $('#echartBox').width(W * 0.55 * 0.65 - 1);
                $('#allmapBox').width(W * 0.55 * 0.35);
                $('#chart').width(W * 0.55 * 0.65 - 1);
                $(window).trigger('resize');
                //				},120)
            });
        });

        $('body').mouseup(function (e) {
            e.cancelBubble = true;
            $(this).unbind("mousemove");
            //			$(window).trigger('resize');
        });
    }
}